package zhibi.cms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zhibi.cms.domain.Menu;
import zhibi.cms.extra.context.Constant;
import zhibi.cms.service.MenuService;
import zhibi.commons.exception.MessageException;
import zhibi.commons.response.JsonResult;
import zhibi.commons.tree.Tree;
import zhibi.frame.mybatis.example.Example;
import zhibi.frame.mybatis.example.ExampleType;
import zhibi.frame.springmvc.base.AbstractController;
import zhibi.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(Constant.SYS_PREFIX + "/menu")
public class CmsMenuController extends AbstractController {

    @Autowired
    private MenuService menuService;

    /**
     * 全部的菜单
     * 菜单树
     *
     * @return
     */
    @RequestMapping("allMenu")
    public JsonResult<List<Tree<Menu>>> allMenu() {
        Example example = Example.getInstance().addOrder("sort", ExampleType.OrderType.DESC)
                .addParam("status", 1);
        List<Menu> menuList = menuService.selectByExample(example);
        //封装成树结构
        List<Tree<Menu>> list = listToTree(menuList, "");
        return JsonResult.success(list);
    }

    /**
     * 得到子菜单
     *
     * @param menuPId
     * @return
     */
    @RequestMapping("pageMenu")
    public JsonResult<Map<String, Object>> pageMenu(String menuPId, String menuId) {
        if (StringUtils.isEmpty(menuPId)) {
            Menu menu = menuService.selectByPrimaryKey(menuId);
            if (menu == null) throw new MessageException("该菜单不存在");
            menuPId = menu.getPid();
        }
        Map<String, Object> map = menuService.selectTreeByPid(menuPId);
        return JsonResult.success(map);
    }


    /**
     * 把数组转换成树
     *
     * @param menuList
     * @param pId
     * @return
     */
    private static List<Tree<Menu>> listToTree(List<Menu> menuList, String pId) {
        List<Tree<Menu>> list = new ArrayList<>();
        for (Menu menu : menuList) {
            if (pId.equals(menu.getPid())) {
                Tree<Menu> child = new Tree<>(menu);
                list.add(child);
                List<Menu> copyList = new ArrayList<>(menuList);
                copyList.remove(menu);
                List<Tree<Menu>> treeList = listToTree(menuList, menu.getId());
                child.addChild(treeList);
            }
        }
        return list;
    }
}
